# -*- coding: utf-8 -*- #
"""
Time                2023/12/04 17:53
Author:             chenshiyan
Email               chenshiyan@linux.alibaba.com
File                main.py
Description:
"""
from clogger import logger
from fastapi import FastAPI
from app.routers import health
from conf.settings import YAML_CONFIG,service_config
from sysom_utils import CmgPlugin, SysomFramework
import traceback
import sys,os,json
sys.path.append("%s/lib"%(os.path.dirname(os.path.abspath(__file__))))
from common import get_group_postlink,postback,timestamp_to_formattime

app = FastAPI()

app.include_router(health.router, prefix="/api/v1/dingtalk/health")
# app.include_router(health.router, prefix="/api/v1/dingtalk/person")

#############################################################################
# Write your API interface here, or add to app/routes
#############################################################################

def dict_to_markdown(jdict):
    retstr = json.dumps(jdict,ensure_ascii=False,indent=4)
    try:
        retstr = "### <font color=#ff6633>SYSOM告警</font>\n\n---\n\n"
        for i in jdict:
            if i == "alert_item":
                retstr = "%s- <font color=#9D9D9D>%s：%s</font>\n\n"%(retstr,"告警条目",jdict[i])
        for i in jdict:
            if i == "alert_category":
                retstr = "%s- <font color=#9D9D9D>%s：%s</font>\n\n"%(retstr,"告警类型",jdict[i])
        for i in jdict:
            if i == "alert_source_type":
                retstr = "%s- <font color=#9D9D9D>%s：%s</font>\n\n"%(retstr,"告警来源",jdict[i])
        for i in jdict:
            if i == "alert_time":
                retstr = "%s- <font color=#9D9D9D>%s：%s</font>\n\n"%(retstr,"告警时间",timestamp_to_formattime(jdict[i]))
        for i in jdict:
            if i == "alert_level":
                retstr = "%s- <font color=#9D9D9D>%s：</font><font color=#FF0000>%s</font>\n\n"%(retstr,"告警等级",jdict[i])
        for i in jdict:
            if i == "labels":
                retstr = "%s\n\n---\n\n- <font color=#9D9D9D>%s</font>\n\n"%(retstr,"告警标签")
                for j in jdict[i]:
                    retstr = "%s&nbsp;&nbsp;&nbsp;&nbsp;<font color=#9D9D9D>%s: %s\n\n</font>"%(retstr,j,jdict[i][j])
        for i in jdict:
            if i == "annotations":
                retstr = "%s\n\n---\n\n- <font color=#9D9D9D>%s</font>\n\n"%(retstr,"告警详情")
                for j in jdict[i]:
                    retstr = "%s&nbsp;&nbsp;&nbsp;&nbsp;<font color=#9D9D9D>%s:</font> <font color=#9D9D9D>%s</font>\n\n"%(retstr,j,jdict[i][j])
                retstr = "%s\n\n---\n\n"%(retstr)
    except Exception as e:
        logger.exception(e)
        traceback.print_exc()
        pass
    return retstr

#@app.post("/api/v1/rca/rca_call")
@app.post("/api/v1/dingtalk/webhook_post")
async def webhook_post(request: dict):
    try:
        print (json.dumps(request,ensure_ascii=False,indent=4))
        ret_msg = {}
        ret_msg["msgtype"] = "markdown"
        ret_msg["markdown"] = {}
        ret_msg["markdown"]["title"] = "SYSOM告警"
        ret_msg["markdown"]["text"] = dict_to_markdown(request)
        for item in service_config.dingtalk:
            webhook = service_config.dingtalk[item].webhook
            sec = service_config.dingtalk[item].sec
            postback(get_group_postlink(webhook,sec),ret_msg)

    except Exception as e:
        logger.exception(e)
        traceback.print_exc()

def init_framwork():
    SysomFramework\
        .init(YAML_CONFIG) \
        .load_plugin_cls(CmgPlugin) \
        .start()
    logger.info("SysomFramework init finished!")

@app.on_event("startup")
async def on_start():
    init_framwork()
    
    #############################################################################
    # Perform some microservice initialization operations over here
    #############################################################################


@app.on_event("shutdown")
async def on_shutdown():
    pass
